package com.hack4jp.hackearthquakes;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;

public class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
	private Context _context;
	private ImageView _image;
    private ProgressBar _progress;
    private String _url;
	
	public DownloadImageTask(Context context, ImageView image, ProgressBar progress)
	{
		_context = context;
		_image = image;
		_progress = progress;
		
		_url = _image.getTag().toString();
	}
	
	@Override
	protected Bitmap doInBackground(String... params) {
		synchronized (_context){
            try {
                Bitmap image = ImageCache.getImage(params[0]);
                if (image == null) {
                    URL imageUrl = new URL(params[0]);
                    InputStream is = imageUrl.openStream();
                    image = BitmapFactory.decodeStream(is);
                    ImageCache.setImage(params[0], image);
                }
                return image;
            } catch (MalformedURLException e) {
                return null;
            } catch (IOException e) {
                return null;
            }
        }
	}

    @Override
    protected void onPostExecute(Bitmap result) {
        // Tagが同じものか確認して、同じであれば画像を設定する
        // （Tagの設定をしないと別の行に画像が表示されてしまう）
        if(_url.equals(_image.getTag())){
            if(result != null){
            	_image.setImageBitmap(result);
            }
            else{
            	_image.setImageDrawable(
            			_context.getResources().getDrawable(
            					R.drawable.icon));
            }
            _progress.setVisibility(View.GONE);
            _image.setVisibility(View.VISIBLE);
        }
    }
}
